package com.wr.async.Test;

import java.util.concurrent.locks.ReentrantLock;

// 可重入锁
public class Lock {
    public static void main(String[] args) {
        TestLock testLock = new TestLock();
        new Thread(testLock,"小李").start();
        new Thread(testLock,"张三").start();
    }
}



class TestLock implements Runnable{

    private int ticketNums = 10;

    // 定义lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            try {
               lock.lock(); // 加锁
                if (ticketNums>0){
                    System.out.println(Thread.currentThread().getName()+"抢到第"+ticketNums--);
                    try {
                        Thread.sleep(1000);
                        double i = 10/0;   // 模拟异常 看释放锁吗
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else {
                    break;
                }
            }finally {
                lock.unlock();  // 解锁
            }

        }
    }
}